package com.aat.dizena.chat.module;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.WebSocketMessage;
import org.springframework.web.socket.WebSocketSession;

import com.aat.dizena.chat.bean.Msg;
import com.alibaba.fastjson.JSONObject;

/**
 * @time 2016-05-25
 * @author 新歌<xingeking@163.com>
 * @email xingeking@163.com
 * @version v1.0
 * @function 基础的controller父类
 * @info java spring websocket
 * @update none
 */
@Component
public class MyWebSocketHandler implements WebSocketHandler {
	public static final Map<String, WebSocketSession> userSocketSessionMap = new HashMap<String, WebSocketSession>();;

	/**
	 * 建立连接后
	 */
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		System.out.println("MyWebSocketHandler 1 ---> " + session.toString());

		String uid = (String) session.getAttributes().get("uid");
		if (userSocketSessionMap.get(uid) == null) {
			userSocketSessionMap.put(uid, session);
		}

	}

	/**
	 * 消息处理，在客户端通过Websocket API发送的消息会经过这里，然后进行相应的处理
	 */
	public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
		System.out.println("MyWebSocketHandler 2 ---> " + session.toString());

		if (message.getPayloadLength() == 0) {
			return;
		}
		Msg msg = JSONObject.parseObject((message.getPayload().toString()), Msg.class);
		msg.setDate(new Date());
		sendMessageToUser(msg.getToUserid(), new TextMessage(JSONObject.toJSONString(msg)));
	}

	/**
	 * 消息传输错误处理
	 */
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		System.out.println("MyWebSocketHandler 3 ---> " + session.toString());

		if (session.isOpen()) {
			session.close();
		}
		Iterator<Entry<String, WebSocketSession>> it = userSocketSessionMap.entrySet().iterator();
		// 移除Socket会话
		while (it.hasNext()) {
			Entry<String, WebSocketSession> entry = it.next();
			if (entry.getValue().getId().equals(session.getId())) {
				userSocketSessionMap.remove(entry.getKey());
				break;
			}
		}
	}

	/**
	 * 关闭连接后
	 */
	public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
		System.out.println("MyWebSocketHandler 4 ---> " + session.toString());

		Iterator<Entry<String, WebSocketSession>> it = userSocketSessionMap.entrySet().iterator();
		// 移除Socket会话
		while (it.hasNext()) {
			Entry<String, WebSocketSession> entry = it.next();
			if (entry.getValue().getId().equals(session.getId())) {
				userSocketSessionMap.remove(entry.getKey());
				break;
			}
		}
	}

	public boolean supportsPartialMessages() {
		return false;
	}

	/**
	 * 给某个用户发送消息
	 */
	public void sendMessageToUser(String uid, TextMessage message) throws IOException {
		System.out.println("MyWebSocketHandler 5 ---> " + uid + " " + message);

		WebSocketSession session = userSocketSessionMap.get(uid);
		if (session != null && session.isOpen()) {
			session.sendMessage(message);
		}
	}

	/**
	 * 给所有在线用户发送消息
	 */
	public void broadcast(String uid, final TextMessage message) throws IOException {

		Iterator<Entry<String, WebSocketSession>> it = userSocketSessionMap.entrySet().iterator();
		// 多线程群发
		while (it.hasNext()) {
			final Entry<String, WebSocketSession> entry = it.next();
			if (entry.getValue().isOpen()) {
				// entry.getValue().sendMessage(message);
				String userid = entry.getKey();

				if (!uid.equals(userid)) {
					// 多线程
					new Thread(new Runnable() {
						public void run() {
							try {
								System.out.println("MyWebSocketHandler 6 ---> " + message.toString());

								if (entry.getValue().isOpen()) {
									entry.getValue().sendMessage(message);
								}
							} catch (IOException e) {

							}
						}

					}).start();
				}

			}

		}
	}

	/**
	 * 给所有在线组内用户发消息
	 */
	public void talkGroup(String uid, String gid, final TextMessage message) throws IOException {

		Iterator<Entry<String, WebSocketSession>> it = userSocketSessionMap.entrySet().iterator();
		// 多线程群发
		while (it.hasNext()) {
			final Entry<String, WebSocketSession> entry = it.next();
			if (entry.getValue().isOpen()) {
				String userid = entry.getKey();

				if (uid != userid && !uid.equals(userid)) {
					// 再一次判断 userid 是否是 gid的 成员,根据gid得到组员的UID
					new Thread(new Runnable() {
						public void run() {
							try {
								System.out.println("MyWebSocketHandler 7 ---> " + message.toString());

								if (entry.getValue().isOpen()) {
									entry.getValue().sendMessage(message);
								}
							} catch (IOException e) {

							}
						}

					}).start();
				}
			}

		}
	}

}